﻿using Common;
using Nest;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ElasticSearch.Core
{
    public class SearchProvider
    {
        public static ElasticClient ElasticClient<T>()
            where T : class
        {
            var uri = new Uri(Config.ElasticSearchAddress);
            var settings = new ConnectionSettings(uri)
                .DefaultIndex(typeof(T).Name.ToLower())
                .DefaultTypeName(typeof(T).Name.ToLower());
            var client = new ElasticClient(settings);
            return client;
        }

        public static IIndexResponse Insert<T>(T model)
            where T : class
        {
            return ElasticClient<T>().IndexDocument(model);
        }

        public static IBulkResponse Insert<T>(List<T> models)
            where T : class
        {
            var req = new BulkRequest();
            foreach (var item in models)
                req.Operations.Add(new BulkIndexOperation<T>(item));
            return ElasticClient<T>().Bulk(req);
        }

        public static IDeleteResponse DeleteById<T>(string id)
            where T : class
        {
            return ElasticClient<T>().Delete(new DocumentPath<T>(new Id(id)));
        }

        public static void DeleteByIds<T>(List<string> ids)
            where T : class
        {
            foreach (var item in ids)
                DeleteById<T>(item);
        }

        public static long GetTotalCount<T>()
            where T : class
        {
            return ElasticClient<T>().Count<T>().Count;
        }
    }
}
